#include <stdio.h>
#include <assert.h>
#include <winsock2.h>
#include <windows.h>

HANDLE hEventThreadExit;

DWORD WINAPI threadTcpIO(LPVOID para) {
	char para1[128];
	SOCKET skt;
	struct sockaddr_in toAddr;
	toAddr.sin_family = AF_INET;
	
	strcpy(para1, para);
	toAddr.sin_port = htons(atoi(strrchr(para1, ' ') + 1));

	*(strrchr(para1, ' ')) = '\0';
	toAddr.sin_addr.S_un.S_addr = inet_addr(para1);

	skt = socket(AF_INET, SOCK_STREAM, 0);
	assert(skt != INVALID_SOCKET);

	if (connect(skt, &toAddr, sizeof(toAddr)) != 0) {
		printf("connect don't return 0\n");
	} else {
		while (1) {
			char buf[128];
			if (WaitForSingleObject(hEventThreadExit, 1000) != WAIT_OBJECT_0) {
				//sprintf(buf, "thread id : %p\n", GetCurrentThreadId());
				//send(skt, buf, strlen(buf), 0);
			} else {
				printf("thread id : %p exit\n", GetCurrentThreadId());
				closesocket(skt);
				break;
			}
		}
	}
	return 0;
}



int main(int argc, char* argv[]) {
	WSADATA wsData;

	if (argc != 4) {
		printf("Usage: %s ip_addr port_number conn_num\n", argv[0]);
		return 0;
	}

	if (0 != WSAStartup(MAKEWORD(2,2), &wsData)) {
		assert(0);
	}

	hEventThreadExit = CreateEvent(0, 1, 0, 0);
	assert(hEventThreadExit);

	{
		HANDLE* threadList;
		int i;
		char buf[128];

		int times = atoi(argv[3]);
		threadList = malloc(sizeof(HANDLE) * times);
		assert(threadList);

		sprintf(buf, "%s %s", argv[1], argv[2]);
		for (i = 0; i < times; ++i) {
			threadList[i] = _beginthreadex(0, 0, threadTcpIO, buf, 0, 0);
			assert(threadList[i]);
		}

		printf("press any key to end ...\n");
		getchar();

		SetEvent(hEventThreadExit);
		for (i = 0; i < times; ++i) {
			WaitForSingleObject(threadList[i], INFINITE);
			CloseHandle(threadList[i]);
		}

		free(threadList);
	}

	WSACleanup();
	return 0;
}